//
//  ImageTunningUp.m
//  OCRReader
//
//  Created by Tomasz Krasnyk on 1/22/10.
//  Copyright 2010 Polidea. All rights reserved.
//

#import "CorrectingSkewView.h"
#import "UIImage+Operations.h"


@interface CorrectingSkewView()
@property (nonatomic, retain) UIImageView *imageView;
@property (nonatomic, retain) UISlider *skewSlider;
@property (nonatomic, retain) UIImage *originalImageScaled;
@property (nonatomic, retain) UIImage *showingImage;
@property (nonatomic, retain) UIScrollView *scrollViewWithImage;
@property (nonatomic, retain) UIImage *originalImage;
@end


@implementation CorrectingSkewView
@synthesize delegate;
@synthesize imageView;
@synthesize skewSlider;
@synthesize originalImageScaled;
@synthesize showingImage;   //dyanic setter
@synthesize scrollViewWithImage;
@synthesize originalImage;
#pragma mark -
#pragma mark get/set
//---------------------------------------------------------------------------------------------
- (void) setShowingImage:(UIImage *) image {
	if(image != showingImage){
		[showingImage release];
		showingImage = [image retain];
		[self.imageView setImage:image];
		
		[self.imageView setFrame:CGRectMake(0.0f, 0.0f, image.size.width, image.size.height)];
		[self.imageView setCenter:self.scrollViewWithImage.center];
	}
}
//---------------------------------------------------------------------------------------------
#pragma mark -
- (id) init {
	return [self initWithOriginalImage:nil];
}

- (id) initWithOriginalImage:(UIImage *) image {
	NSAssert(image, @"image can't be nil");
	if(self = [super init]){
		self.originalImage = image;		//on this image we do conversions
		
		CGFloat maximumSize = 320;		//size of the image we show in the view
		CGFloat maximumImageSize = MAX(image.size.width, image.size.height);
		CGFloat scaleFactor = maximumSize/(maximumImageSize+0.001f);
		
		CGSize mySize = CGSizeMake((NSInteger)(image.size.width * scaleFactor), (NSInteger)(image.size.height * scaleFactor));
		UIGraphicsBeginImageContext(mySize);
		
		CGContextRef context = UIGraphicsGetCurrentContext();
		UIGraphicsPushContext(context);
		[image drawInRect:CGRectMake(0.0f, 0.0f, mySize.width, mySize.height)];
		UIGraphicsPopContext();
		
		self.originalImageScaled = UIGraphicsGetImageFromCurrentImageContext();
		UIGraphicsEndImageContext();
		
		self.title = NSLocalizedString(@"Rotate image", nil);
	}
	return self;
}

- (void) setupToolbar {
	UIBarButtonItem *autoSkew = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Auto", nil) style:UIBarButtonItemStyleBordered target:self action:@selector(autoSkew)];
	UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:NULL];
	
	NSArray *array = [[NSArray alloc] initWithObjects:flexibleSpace, autoSkew, nil];
	[autoSkew release];
	[flexibleSpace release];
	
	[self setToolbarItems:array animated:YES];
	[array release];
}

- (void) loadView {
	[super loadView];
	
	[self setupToolbar];
	
	self.scrollViewWithImage = [[UIScrollView alloc] initWithFrame:self.view.bounds];
	[self.scrollViewWithImage release];
	
	self.imageView = [[UIImageView alloc] init];
	[self.imageView release];
	[self.scrollViewWithImage addSubview:self.imageView];

	[self.view addSubview:self.scrollViewWithImage];
	
	CGFloat sliderHeight = 44.0f;
	self.skewSlider = [[UISlider alloc] initWithFrame:CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.view.bounds), sliderHeight)];
	[self.skewSlider release];
	[self.skewSlider addTarget:self action:@selector(sliderValueChanged) forControlEvents:UIControlEventValueChanged];
	[self.skewSlider setMinimumValue:-90.0f];
	[self.skewSlider setMaximumValue:90.0f];
	[self.skewSlider setValue:0.0f];

	[self.view addSubview:self.skewSlider];
}

- (void) viewDidLoad {
	UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"save", @"title on save button in tunning up controller") style:UIBarButtonItemStyleBordered target:self action:@selector(saveClicked)];
	[saveButton setEnabled:self.skewSlider.value != 0.0f];
	self.navigationItem.rightBarButtonItem = saveButton;
	[saveButton release];
	
	self.showingImage = self.originalImageScaled;
}

- (void) sliderValueChanged {
	[self.imageView setTransform:CGAffineTransformMakeRotation(-self.skewSlider.value * M_PI / 180)];
	
	[self.navigationItem.rightBarButtonItem setEnabled:self.skewSlider.value != 0.0f];
}

- (void) autoSkew {
	CGFloat detectedAngle = 0;
	//first detection, threshold 10 degrees
	UIImage *imageToProcess = self.originalImageScaled;
	CGFloat angle = [UIImage detectSkewOfTheImage:imageToProcess withDegreesRangeMinimum:0 andDegreesMaximum:45 degreesStep:5];
	detectedAngle += angle;
	[self.skewSlider setValue:angle];
	[self sliderValueChanged];
	
	//self.changedImage = [UIImageConverter convertTo8bppGrayscaleFromImage:[UIImage rotateImage:imageToProcess byDegrees:-angle] forceScale:NO];
	/*//2nd detection, treshold 3 degrees
	 angle = [UIImageConverter detectSkewOfTheImage:self.imageToOperateOn withDegreesRangeMinimum:1 andDegreesMaximum:12 degreesStep:3];
	 detectedAngle += angle;
	 UIImage *secondFilter = [UIImageConverter convertTo8bppGrayscaleFromImage:[UIImage rotateImage:self.imageToOperateOn byDegrees:-angle]];
	 self.imageToOperateOn = secondFilter;
	 //3rd filter, treshold, 1 deg
	 angle = [UIImageConverter detectSkewOfTheImage:self.imageToOperateOn withDegreesRangeMinimum:2 andDegreesMaximum:5 degreesStep:1];
	 detectedAngle += angle;
	 UIImage *thirdFilter = [UIImageConverter convertTo8bppGrayscaleFromImage:[UIImage rotateImage:self.imageToOperateOn byDegrees:-angle]];
	 self.imageToOperateOn = thirdFilter;*/
	
	
	//self.imageToOperateOn = [UIImageConverter convertTo8bppGrayscaleFromImage:[UIImage rotateImage:self.imageToOperateOn byDegrees:-angle]];
	//[self.viewWithSelectedImage setTransform:CGAffineTransformMakeRotation(-(angle*M_PI)/180.0f)];
	
	//self.showingImage = self.changedImage;
}

- (void) saveClicked {
	if(self.delegate){
		UIImage *conv = [[UIImage rotateImage:self.originalImage byDegrees:-self.skewSlider.value] retain];
		[self.delegate imageTunningUpControllerChangedImageTo:conv];
		[conv release];
	} else {
		NSLog(@"WARNING delegate of the TUnningUpClass has not been set up!");
	}
	[self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {

}


- (void)dealloc {
	[originalImage release];
	[showingImage release];
	
	[scrollViewWithImage release];
	[originalImageScaled release];
	
	[skewSlider release];
	[imageView release];
	self.delegate = nil;
    [super dealloc];
}

@end
